import { defineStore } from 'pinia';
import user from './user'
import washApi from '@/sheep/api/wash';
import {showAuditModal} from '@/sheep/hooks/useAudit.js'
import { wgs84ToGcj02 } from '@/sheep/helper/index.js'
const wash = defineStore({
  id: 'wash',
  state: () => ({
    deviceId:'',
    // 当前设备
    data:{},
    // 当前位置
    myPosition:{
      latitude:'',
      longitude:''
    },
  }),
  getters: {
  },
  actions: {
    async upDateExamine(info){
        // let {data} = await washApi.examineState({device: info})
        // this.examine = data ? !!(data.examine_status*1) : false 
    },
    setDevice(data){
      this.deviceId = data.id;
      this.data = data;
      this.updateDevice()
    },
    async updateDevice(){
      let res = await washApi.getMachineInfo({machine_code:this.data.code})
      if(res.error==0){
        this.data = res.data;
      }
    },
    async getPetInfo(id=this.petId) {
      // if(!id)return
      // let {data} = await washApi.petDetails({
      //   id
      // })
      // this.petInfo = data
      // return data
    },
    async getDeviceList(page) {
      // if(!user().isLogin)return
      // let {data} = await washApi.getSettings()
      // if(data){
      //   this.deviceList = data
      //   if(!data.length){
      //     this.petId = ''
      //     this.petInfo = {}
      //     return
      //   }
      //   this.setPet()
      // }
    },
    // 定位
    getLocation() {
      return new Promise((resolve,reject)=>{
        const location = ()=>{
          uni.showLoading({
            title: '定位中',
            mask: true
          })
          uni.getLocation({
            // type: 'gcj02',
			//仅App平台支持,微信小程序不支持此参数
            geocode: false,
            success: (res) => {
				console.log('res:',res);
				uni.hideLoading()
				let [ lng , lat ] = wgs84ToGcj02(res.longitude,res.latitude)
				this.myPosition.longitude = lng;
				this.myPosition.latitude = lat;
				resolve({
					...res,
					longitude:lng,
					latitude:lat,
				})
            },
            fail: (err) => {
			  uni.hideLoading()
              uni.showToast({
                title: '定位失败,请退出重试',
                icon: 'none'
              })
              reject(err)
            }
          })
        }
		// #ifdef APP
		
		showAuditModal('ACCESS_FINE_LOCATION',()=>{
			location()
		},()=>{
			reject()
		})
		// #endif
        // #ifdef MP		
        uni.getSetting({
          scope: 'scope.userLocation',
          success(res) {
			  console.log('res:',res);
			  if(res.authSetting['scope.userLocation']){
				  location()
			  }else{
				  uni.authorize({
					  scope: 'scope.userLocation',
					  success: function (authorizeREs) {
						  console.log('authorizeREs:',authorizeREs)
						// 授权成功后重新获取位置
						location();
					  },
					  fail: function (authorizEerror) {
						  console.log('authorizEerror:',authorizEerror);
						// 授权失败，提示用户手动开启权限
						uni.showModal({
							title: '温馨提示',
							content: '请先授权定位权限',
							success: function (modalRes) {
								if (modalRes.confirm) {
									uni.openSetting({
									  success(result) {
									    if(result.authSetting['scope.userLocation']){
									      location()
									    }
									  },
									  fail(error){
										  uni.showToast({
										    title: '授权失败',
										    icon: 'none'
										  })
										  reject(error)
									  }
									})
								} else if (res.cancel) {
									console.log('定位点击取消');
								}
							}
						});
					  }
					});
			  }
          }
        })
      // #endif
	  // #ifdef H5
	  location();
	  // #endif
	 
      })
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'wash-store',
        storage: localStorage, //存储的位置，默认为sessionStorage
      },
    ],
  },
});

export default wash;
